package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.CiticConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.citic.ebank.pay.CiticB2bMessage;
import com.gopay.common.domain.bank.citic.ebank.query.res.RowRes;
import com.gopay.common.domain.bank.citic.ebank.query.res.data.CiticB2bStreamDataRes;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * @CheckOrderCiticB2bImpl.java
 * @author wanggang
 * @2013-12-6 下午4:44:15 www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderCiticB2bImpl implements BankOrderService {

	private final static Logger logger = LoggerFactory.getLogger("CITIC");

	@Resource(name = "bankClient")
	private BankInteractRemoteService bankClient;
	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());
		try {
			CiticB2bMessage base = new CiticB2bMessage();
			base.setOrderId(bankOrder.getOrderId());
			base.setBankOrderId(bankOrder.getOutOrderId());
			base.setBank(BankConstants.BANK_LOGO_CITIC);
			base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
			base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
			Result result = new Result();
			result = bankClient.query(base);
			if (result == null || !result.isSuccess()) {
				logger.debug("bankClient fail.");				
				if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
					checkOrderResult.setCommunicateError(true);
	            }				
				logger.debug(ToStringBuilder.reflectionToString(result,ToStringStyle.DEFAULT_STYLE));
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}
			CiticB2bStreamDataRes res = (CiticB2bStreamDataRes) result.getDefaultModel();
			if (res == null) {
				// 查询订单为空
				logger.debug("中信银行B2B对账失败，返回为null，orderId："+ bankOrder.getOrderId() + " errcode:"+ ProcCodeConstants.PROC_CODE_100E5062+ " err:bis query is null.");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
				checkOrderResult.setErrMsg("银行返回对账结果为空");
			}
			String trnxStatus = res.getStatus(); // 该笔订单查询交易的状态
			if (!CiticConstants.SUCCESS.equals(trnxStatus)) {
				// 查询订单错误
				logger.debug("(Web模式订单查询--B2B--中信银行)查询订单 = "+ bankOrder.getOrderId() + "失败.查询交易状态:"+ res.getStatus() + "查询交易描述：" + res.getTxnStatus());
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
				checkOrderResult.setErrMsg(res.getTxnStatus());
				return checkOrderResult;
			}
			// 中信B2B查询对象
			RowRes orderDetail = (RowRes) res.getData().getRows();
			String orderStatus = orderDetail.getStt(); // 该笔订单的交易状态
			if (!StringUtils.isBlank(orderStatus)) {
				// 成功
				if (orderStatus.equals(CiticConstants.ORDER_STATUS_SUCCESS)) {
					logger.info("中信银行B2B订单:" + res.getMctJnNo() + "交易成功("+ orderStatus + ")");
					String amount = res.getData().getRows().get(0).getTranAmt(); // 银行交易金额
					checkOrderResult.setSuccess(true);
					InAccInfo accInfo = new InAccInfo();
					accInfo.setOrderId(bankOrder.getOrderId());
					accInfo.setAmount(new BigDecimal(amount));
					accInfo.setRetCode("00");
					accInfo.setCardType(BankCardType.Unknown.toString());
					checkOrderResult.setAccInfo(accInfo);
				}
				// 未确认
				else if (orderStatus.equals(CiticConstants.ORDER_STATUS_UNCONFIRM)) {
					logger.info("中信银行B2B订单:" + res.getMctJnNo()+ "订单状态为：未确认，有待后续继续查询(" + orderStatus + "状态描述："+ orderDetail.getStatus() + ")");
					checkOrderResult.setErrMsg("银行返回交易未确认");
				}
				// 交易失败
				else if (orderStatus.equals(CiticConstants.ORDER_STATUS_FAIL)) {
					checkOrderResult.setBankFailure(true);
					logger.info("中信银行B2B订单:" + res.getMctJnNo() + "交易失败("+ orderStatus + ")");
					checkOrderResult.setErrMsg("银行返回交易失败");
				}
				// 未知
				else {
					logger.info("中信银行B2B订单:" + res.getMctJnNo()+ "订单状态为：未知，有待后续继续查询(" + orderStatus + "状态描述："+ orderDetail.getStatus() + ")");
					checkOrderResult.setErrMsg("银行返回交易未知");
				}
			}
			return checkOrderResult;
		} catch (Exception e) {
			logger.debug("bankClient fail.", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("对账调用bis失败");
			return checkOrderResult;
		}
	}
	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}
}
